<template>
  <div class="common-upload">
    <a-upload
      v-model:file-list="fileList"
      name="file"
      :maxCount="1"
      list-type="picture-card"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :customRequest="customRequest"
      @change="changeHandel"
      :disabled="disabled"
    >
      <img v-if="props.value" :src="props.value" alt="avatar" />
      <div v-else>
        <plus-outlined></plus-outlined>
      </div>
    </a-upload>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { Upload, UploadMinio } from "@/api/common";
const props = defineProps(["value", "disabled"]);
const emit = defineEmits(["update:value"]);
const fileList = ref([]);
// 自定义上传
const customRequest = (e) => {
  const isJpgOrPng =
    e.file.type === "image/jpeg" || e.file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("只能上传jpg/png文件");
    return;
  }
  const isLt2M = e.file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片大小不能超过 2MB!");
    return;
  }

  const formData = new FormData();
  formData.append("file", e.file);
  UploadMinio(formData)
    .then((res) => {
      const { success, data, msg } = res;
      if (success) {
        const addFile = {
          ...e.file,
          status: "done",
          ...res,
        };
        console.log("1111", addFile);
        e.onSuccess(addFile);
      } else {
        e.onError();
      }
    })
    .catch((err) => {
      e.onError(err);
    });
};

const changeHandel = ({ file }) => {
  console.log(file, "file");
  if (file.status === "done") {
    const { response } = file;
    if (response.success) {
      emit("update:value", response.data);
    }
  }
};
const beforeUpload = (file) => {};
</script>
<style lang="scss" scoped>
.ant-upload {
  img {
    width: 102px;
    height: 102px;
    border-radius: 4px;
  }
}
</style>